package com.zh.eventdispatch.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

/**
 * @author wally
 * @date 2021/06/20
 */
public abstract class EventDispatcherFragment extends Fragment implements ActivityEventObserver {
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ActivityEventOwner owner = getActivityEventOwner();
        if (owner != null) {
            owner.getEventDispatcher().addObserver(this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ActivityEventOwner owner = getActivityEventOwner();
        if (owner != null) {
            owner.getEventDispatcher().removeObserver(this);
        }
    }

    protected ActivityEventOwner getActivityEventOwner() {
        FragmentActivity activity = getActivity();
        if (activity instanceof ActivityEventOwner) {
            return (ActivityEventOwner) activity;
        }
        return null;
    }

    @Override
    public boolean onSupportActivityResult(int requestCode, int resultCode, Intent data) {
        return false;
    }

    @Override
    public boolean onSupportBackPressed() {
        return false;
    }
}